<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: liguohua@clcw.com.cn  Blog:http://blog.sina.com.cn/saverneo        |
// +------------------------------------------------------------------------+
//
//用户登录
namespace AuctionAppApi\Controller;

use AuctionCore\Common\PhpRedis;
use Think\Controller;
use AuctionCore\System\AuctionException;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\CarResource\Car;
use AuctionCore\CarResource\CarModel;
use AuctionCore\Other\Address;
use AuctionCore\CarDealer\Dealer;


/**
 * 拍单接口
 */
class AuctionController extends BaseController {

    public function __construct(){
        parent::__construct();
    }
    public function index() {
    }

    /**
     *    拍单列表
     *    $stat 根据查询返回拍单个数 缺省 false
     */
    public function get_list($stat=false) {
        //
        $type = I('post.type');
        $page = I('post.page', '1');
        $page_size = I('post.page_size', '20');
        //搜索条件
        $arr = $this->get_map();
        $map = $arr[0];

        $cm = new \AuctionCore\CarResource\CarModel();
        $addr = new \AuctionCore\Other\Address();
        $dObj = new \AuctionCore\CarDealer\Dealer($this->dealer_id);
        //dump($map);
        //计算符合条件的记录总数
        $total = M('order')->alias('o')->join(C('DB_PREFIX') . "cars c On o.car_id=c.car_id")
            ->join(C('DB_PREFIX') . "order_scene os On os.scene_id=o.scene_id")->where($map)->count();
        //echo M()->getLastSql();
        $title = '竞拍中的拍单';
        if($type=='4' && $total <=0 ){
            //获取最近场的投标单
            $scene = $this->get_last_scene($map['c.location_area'][1]);
            $map['o.scene_id'] = $scene['scene_id'];
            //获取状态为3的拍单
            $map['o.status'] = '3'; //投标
            $title = '最近场次-'.$scene['name'];
            //没有竞标中的，需要查询一下投标中的拍单数量
            $total = M('order')->alias('o')->join(C('DB_PREFIX') . "cars c On o.car_id=c.car_id")
                ->join(C('DB_PREFIX') . "order_scene os On os.scene_id=o.scene_id")->where($map)->count();
        }
        if($stat){
            return $total;
        }
        $offset = ($page - 1) * $page_size;
        $limit_value = $offset . "," . $page_size;

        $cols = "o.order_id,o.order_no,o.scene_id,o.status,os.starttime,
                    o.bid_start_price,o.bidding_best_price,o.bidding_start_time,o.act_elapsed_time,o.est_elapsed_time,o.coupon,o.rank,o.is_timing_order,o.show_reserve_price,
                    c.series_id,c.car_id,c.car_no,c.reg_city,c.first_reg_date,c.pointer_mileage,c.location_area,
                    c.plate_prefix,c.plate_suffix,c.composite_state,c.accident_level,c.car_cc,c.turbo,c.gearbox";
        $res = M('order')->alias('o')->field($cols)->join(C('DB_PREFIX') . "cars c On o.car_id=c.car_id")
            ->join(C('DB_PREFIX') . "order_scene os ON os.scene_id=o.scene_id")
            ->where($map)->order("FIND_IN_SET(o.status,'4,301,3'),os.starttime,os.scene_id,o.bidding_start_time,o.order_id")->limit($limit_value)->select();
            //echo M()->getLastSql();
        $list = array();

        foreach ($res as $key => $value) {
            $list[$key]['order_id'] = $value['order_id'];
            $list[$key]['order_no'] = $value['order_no'];
            //品牌车系车型
            $series = $cm->get_model_by_id($value['series_id'], 'series');
            //品牌车系车型
            $location_area = '['.$addr->get_name_by_code($value['location_area']).']';
            $list[$key]['car_name'] = $location_area.$series['name'] . ' ' . $value['car_cc'] . ($value['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $value['gearbox']);
            //初登日期
            $list[$key]['first_reg_date'] = date('Y年m月', strtotime($value['first_reg_date']));
            //公里数格式转换
            $list[$key]['pointer_mileage'] = convert_mileage($value['pointer_mileage']);

            $list[$key]['plate_number'] = C('PLATE_PREFIX.' . $value['plate_prefix']) . substr($value['plate_suffix'], 0, 1);

            $list[$key]['desc'] = $list[$key]['first_reg_date'].'初登/'.$list[$key]['pointer_mileage'].'万公里/'.$list[$key]['plate_number'];

            ///汽车缩略图(不加oss图片处理参数)
            $car = new \AuctionCore\CarResource\Car($value['car_id']);
            $cond = "car_id='" . $value['car_id'] . "' AND pic_key='p_left_front45'";
            $pics = $car->get_pics('car_pictures', $cond);
            $list[$key]['img'] = $pics[0]['pic_url'];
            //是否关注
            $list[$key]['is_followed'] = $dObj->is_followed($value['order_id']) ? 1 : 0 ;
            //车况等级
            $list[$key]['composite_level'] = $value['composite_state'] . $value['accident_level'];
            //是否能用代金券
            $list[$key]['use_coupon'] = $value['coupon'] > 0 ? true : false;
            ///拍单状态（1:投标中、2:待竞拍、3:竞标中）
            $state = 0;
            $price = $value['bid_start_price'];
            switch ($value['status']) {
                case '3':
                    $state = 1;
                    break;
                case '301':
                    $state = 2;
                    break;
                case '4':
                    $state = 3;
                    if ($value['bidding_best_price'] > $price) {
                        $price = $value['bidding_best_price'];
                    }
                    break;
            }
            $list[$key]['state'] = $state;
            //当前价格
            $list[$key]['price'] = strip_tags(format_money($price)).'元';

            /*************************计算剩余时间**********************************/
            if($value['status']=='3'){
                //投标倒计时
                $t = strtotime($value['starttime'])-time();
            }elseif($value['status']=='4'){
                //竞标倒计时
                $elapsed_time = $value['act_elapsed_time']>$value['est_elapsed_time']?$value['act_elapsed_time']:$value['est_elapsed_time'];
                $t = strtotime($value['bidding_start_time'])+$elapsed_time-time();
            }else{
                $t = -2;
            }

            //结束时间（竞拍结束时间、投标结束时间 时间戳）
            $list[$key]['remaining_time'] = ($t+2)*1000;

            //是否显示保留价
            $list[$key]['show_reserve_price'] = $value['show_reserve_price']>0?true:false;
        }
        $data = array();
        $data['title'] = $title;
        $list_filter = array_filter($list);
        if(empty($list_filter)){
             $data['title'] = "";
        }
        $data['currentpage'] = $page;
        $data['pagesize'] = $page_size;
        $data['maxcount'] = $total;
        $data['maxpage'] = ceil($total / $page_size);
        $data['list'] = $list;
        
        //输出json数据
        $this->api_200($data);
    }
    /**
     *    拍单列表
     *    $stat 根据查询返回拍单个数 缺省 false
     */
    public function get_list_v130($stat=false) {
        //
        $type = I('post.type');
        $page = I('post.page', '1');
        $page_size = I('post.page_size', '20');
        //搜索条件
        $arr = $this->get_map();
        $map = $arr[0];
        $f_j_orders = (is_array($arr[1]) && $arr[1]) ? implode(',',$arr[1]) : '';
        $cm = new CarModel();
        $addr = new Address();
        $dObj = new Dealer($this->dealer_id);
        //dump($map);
        //计算符合条件的记录总数
        $total = M('order')->alias('o')->join(C('DB_PREFIX') . "cars c On o.car_id=c.car_id")
            ->join(C('DB_PREFIX') . "order_scene os On os.scene_id=o.scene_id")->where($map)->count();
        //echo M()->getLastSql();
        $title = '竞拍中的拍单';
        $cnt = 0;
        if($type=='4' && $total == 0 ){
            //获取最近场的投标单
            $scene = $this->get_last_scene($map['c.location_area'][1]);
            $map['o.scene_id'] = $scene['scene_id'];
            //获取状态为3的拍单
            $map['o.status'] = '3'; //投标
            $title = '最近场次-'.$scene['name'];
            //没有竞标中的，需要查询一下投标中的拍单数量
            $cnt = M('order')->alias('o')->join(C('DB_PREFIX') . "cars c On o.car_id=c.car_id")
                ->join(C('DB_PREFIX') . "order_scene os On os.scene_id=o.scene_id")->where($map)->count();
        }
        if($stat){
            return $cnt;
        }
        $offset = ($page - 1) * $page_size;

        if($type==5){
            $order = $f_j_orders?"FIND_IN_SET(o.order_id,'".$f_j_orders."')":'';
            $limit_value = '';
        }else{
            $order_bidding = "left_time,o.order_id";
            $order_bid = "os.starttime,os.scene_id,bidding_start_time,o.order_id";
            $limit_value = "limit ".$offset . "," . $page_size;
        }

        $cols = "o.order_id,o.order_no,o.scene_id,o.status,os.starttime,o.transfer_fee,o.bidding_best_dealer_id,
                    o.bid_start_price,o.bidding_best_price,o.bidding_start_time,o.act_elapsed_time,o.est_elapsed_time,o.coupon,o.rank,o.is_timing_order,o.show_reserve_price,
                    c.series_id,c.car_id,c.car_no,c.reg_city,c.first_reg_date,c.pointer_mileage,c.location_area,
                    c.plate_prefix,c.plate_suffix,c.composite_state,c.accident_level,c.car_cc,c.turbo,c.gearbox";
        $bidding_cols = ",UNIX_TIMESTAMP(o.bidding_start_time)+IF(o.act_elapsed_time>o.est_elapsed_time,o.act_elapsed_time,o.est_elapsed_time) - UNIX_TIMESTAMP(NOW()) AS left_time";
        $bid_cols = ",'left_time'";
        $map['o.status'] = '4';

        if($type==4){
            if($total==0){//获取最近场内投标单
                $map['o.status'] = '3';
            }
            $res = M('order')->alias('o')->field($cols.$bidding_cols)->join(C('DB_PREFIX') . "cars c On o.car_id=c.car_id")
                ->join(C('DB_PREFIX') . "order_scene os ON os.scene_id=o.scene_id")
                ->where($map)->order($type!=5?$order_bidding:$order)->select();
        }else{
            $sql1 = M('order')->alias('o')->field($cols.$bidding_cols)->join(C('DB_PREFIX') . "cars c On o.car_id=c.car_id")
                ->join(C('DB_PREFIX') . "order_scene os ON os.scene_id=o.scene_id")
                ->where($map)->order($type!=5?$order_bidding:$order)->select(false);
            $map['o.status'] = array('in','3,301');
            unset($map['o.status']);
            $sql2 = M('order')->alias('o')->field($cols.$bid_cols)->join(C('DB_PREFIX') . "cars c On o.car_id=c.car_id")
                ->join(C('DB_PREFIX') . "order_scene os ON os.scene_id=o.scene_id")
                ->where("FIND_IN_SET(o.status,'301,3')")->where($map)->order($type!=5?$order_bid:$order)->select(false);

            $sql = "(SELECT * FROM $sql1  AS bidding) UNION ALL (SELECT * FROM $sql2 AS bid) $limit_value";
            $res = M()->query($sql);
        }

        $list = array();
        foreach ($res as $key => $value) {
            $list[$key]['order_id'] = $value['order_id'];
            $list[$key]['order_no'] = $value['order_no'];
            //品牌车系车型
            $series = $cm->get_model_by_id($value['series_id'], 'series');
            //品牌车系车型
            $location_area = '['.$addr->get_name_by_code($value['location_area']).']';
            $list[$key]['car_name'] = $location_area.$series['name'] . ' ' . $value['car_cc'] . ($value['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $value['gearbox']);
            //初登日期
            $list[$key]['first_reg_date'] = date('Y年m月', strtotime($value['first_reg_date']));
            //公里数格式转换
            $list[$key]['pointer_mileage'] = convert_mileage($value['pointer_mileage']);

            $list[$key]['plate_number'] = C('PLATE_PREFIX.' . $value['plate_prefix']) . substr($value['plate_suffix'], 0, 1);

            $list[$key]['desc'] = $list[$key]['first_reg_date'].'初登/'.$list[$key]['pointer_mileage'].'万公里/'.$list[$key]['plate_number'];

            ///汽车缩略图(不加oss图片处理参数)
            $car = new Car($value['car_id']);
            $cond = "car_id='" . $value['car_id'] . "' AND pic_key='p_left_front45'";
            $pics = $car->get_pics('car_pictures', $cond);
            $list[$key]['img'] = get_content_cdnurl().$pics[0]['pic_url'];
            //是否关注
            $list[$key]['is_followed'] = $dObj->is_followed($value['order_id']) ? 1 : 0 ;
            //车况等级
            $list[$key]['composite_level'] = $value['composite_state'] . $value['accident_level'];
            //是否能用代金券
            $list[$key]['use_coupon'] = $value['coupon'] > 0 ? true : false;
            //查看是否智能出价
            $redis = new PhpRedis();
            $arr = ['order_id'=>$value['order_id']];
            $key1 = getRedisKeyByCode('REDIS_KEY','100002',$arr);
            $zhi_list = $redis->zrange($key1,0,-1);
            if(in_array($this->dealer_id,$zhi_list)){
                $list[$key]['is_auto_bidding'] = true; //增加智能报价标签
            }else{
                $list[$key]['is_auto_bidding'] = false;
            }
            ///拍单状态
            $list[$key]['bidding_best_dealer_id'] = $value['bidding_best_dealer_id'];
            $list[$key]['state'] = $value['status'];
            //起拍价
            $list[$key]['bid_start_price'] = $value['bid_start_price'];

            switch ($value['status']) {
                case '3':
                    $list[$key]['status_cn'] = '投标中';
                    $my_last_bid_price = $dObj->get_my_last_bid_price($value['order_id']);
                    $list[$key]['my_last_bid_price'] = floatval($my_last_bid_price);
                    //交易服务费
                    $list[$key]['commision'] = $my_last_bid_price>0? get_commision($my_last_bid_price,$value['starttime']):get_commision($value['bid_start_price'],$value['starttime']);
                    //当前价
                    $price = $my_last_bid_price>0 ?$my_last_bid_price:$value['bid_start_price'];
                    break;
                case '301':
                    $list[$key]['status_cn'] = '待竞拍';
                    //交易服务费
                    $list[$key]['commision'] = get_commision($value['bid_start_price']);
                    //当前价
                    $price = $value['bid_start_price'];
                    break;
                case '4':
                    $list[$key]['status_cn'] = '竞拍中';

                    $my_last_bid_price = $dObj->get_my_last_bid_price($value['order_id']);
                    $list[$key]['my_last_bid_price'] = floatval($my_last_bid_price);

                    $my_last_bidding_price = $dObj->get_my_last_bidding_price($value['order_id']);
                    $list[$key]['my_last_bidding_price'] = floatval($my_last_bidding_price);
                    //交易服务费
                    $list[$key]['commision'] = get_commision($value['bidding_best_price']>0? $value['bidding_best_price']:$value['bid_start_price']);
                    //当前价
                    $price = $value['bidding_best_price']>$value['bid_start_price']?$value['bidding_best_price']:$value['bid_start_price'];
                    break;
            }
            //当前价格
            $list[$key]['price'] = intval($price);
            //交付服务费
            $list[$key]['transfer_fee'] = intval($value['transfer_fee']);
            /*************************计算剩余时间**********************************/
            //结束时间（竞拍结束时间、投标结束时间 时间戳）
            $list[$key]['starttime'] = strtotime($value['starttime'])*1000;
            $list[$key]['bidding_start_time'] = strtotime($value['bidding_start_time'])*1000;
            $list[$key]['act_elapsed_time'] = $value['act_elapsed_time']*1000;
            $list[$key]['est_elapsed_time'] = $value['est_elapsed_time']*1000;

            //是否显示保留价
            $list[$key]['show_reserve_price'] = $value['show_reserve_price']>0?true:false;
        }
        $data = array();
        $data['title'] = $title;
        $list_filter = array_filter($list);
        if(empty($list_filter)){
             $data['title'] = "";
        }
        $data['currentpage'] = $page;
        $data['pagesize'] = $page_size;
        $data['maxcount'] = $total;
        $data['maxpage'] = ceil($total / $page_size);
        $data['list'] = $list;

        //输出json数据
        $this->api_200($data);
    }



    //获取最近场ID
    private function get_last_scene($city=''){
            $scene = new \AuctionCore\AuctionOrder\Scene();
            return $scene->get_last_scene($city);
    }
    /**
     * 获取查询条件映射
     * @autor Eric
     * @return array
     */
    private function get_map() {
        $type = I('post.type');//1:关注、2:出过价的、3:特定场次、4:首页列表
        $day = I('post.day');//0:全部、1:今日、2:明日
        $scene_id = I('post.scene_id');//场次ID
        $mbrand_id = I('post.mbrand_id');//主品牌ID
        $series_id = I('post.series_id');//车系ID
        $emission_std = I('post.emission');//排放标准（多选）
        $price_range = I('post.prices_interval');//推荐价格区间（多选）
        $custom_low_price = I('post.custom_low_price');//自定义最低价
        $custom_high_price = I('post.custom_high_price');//自定义最高价
        $age_range = I('post.year_interval');//年限（多选）
        $condition_level = I('post.condition_level');//车况等级（多选）
        $location_area = I('post.branch_company');//车辆所在地(多选)
        //条件
        $map = array();
        $map['o.status'] = array('in', '3,4,301');
        $map['os.status'] = array('in', '1,2');//场次状态 -1禁用 1待拍 2拍卖中 3 完成

         //场时间
        $date = '';
        if ($day > 0) {
            switch ($day) {
                case '1':
                    $date = date('Y-m-d');
                    break;
                case '2':
                    $date = date('Y-m-d', strtotime('+1 day'));
                    break;
            }
            $map['os.starttime'] = array('between', array($date . ' 00:00:00',$date . ' 23:59:59'));
        }
        switch($type){
            case '1':
                    if(!$this->dealer_id){
                        AuctionException::make_throw('500001');
                    }
                    $dObj = new \AuctionCore\CarDealer\Dealer($this->dealer_id);
                    $followed_orders = $dObj->my_followed_auction();
                    $followed_orders = is_array($followed_orders) && $followed_orders ? $followed_orders : array(0);
                    $map['o.order_id'] = array('in', $followed_orders);
                break;
            case '2':
                    if(!$this->dealer_id){
                        AuctionException::make_throw('500001');
                    }
                    $dObj = new \AuctionCore\CarDealer\Dealer($this->dealer_id);
                    $joined_orders = $dObj->my_joined_auction();
                    $joined_orders = (is_array($joined_orders) && $joined_orders) ? $joined_orders : array(0);
                    $map['o.order_id'] = array('in', $joined_orders);
                break;
            case '3':
                    $map['os.scene_id'] = array('eq', $scene_id);
                break;
            case '4':
                    $map['o.status'] = array('eq', '4');
                break;
            case '5':
                    if(!$this->dealer_id){
                        AuctionException::make_throw('500001');
                    }
                    $dObj = new \AuctionCore\CarDealer\Dealer($this->dealer_id);
                    $f_j_orders = $dObj->get_f_j_orders($map);
                    $map['o.order_id'] = array('in', $f_j_orders);
                break;
        }

        if ($mbrand_id) {
            $map['c.mbrand_id'] = array('eq', $mbrand_id);
        }
        if ($series_id) {
            $map['c.series_id'] = array('eq', $series_id);
        }
        if($emission_std){
            $emission_std = explode(',',$emission_std);
            $this->emission_std_map($map,$emission_std);
        }
        if($price_range || $custom_high_price || $custom_low_price){
            if($price_range){
                $price_range = explode(',',$price_range);
            }
            $this->price_range_map($map,$price_range,$custom_high_price,$custom_low_price);
        }
        if($age_range){
            $age_range = explode(',',$age_range);
            $this->age_range_map($map,$age_range);
        }
        if($condition_level){
            $condition_level = explode(',',$condition_level);
            $this->condition_level_map($map,$condition_level);
        }
        if($location_area && $location_area != '-1'){
            $map['c.location_area'] = array('in',$location_area);
        }
        return array($map,$f_j_orders);
    }

    /**
     * 处理排放查询条件
    */
    private  function emission_std_map(&$map,$emission_std=array()){
            if ($emission_std && is_array($emission_std)) {
                if(!in_array('-1',$emission_std)){
                    $map['c.emission'] = array('in', $emission_std ? $emission_std : array(0));
                }
            }
    }
    /**
     * 处理价格区间查询条件
     */
    private function price_range_map(&$map,$price_range=array(),$custom_high_price='',$custom_low_price=''){
            if($custom_low_price && !$custom_high_price){
                $map['o.bid_start_price'] = array('egt', $custom_low_price*10000);
            }elseif(!$custom_low_price && $custom_high_price){
                $map['o.bid_start_price'] = array('elt', $custom_high_price*10000);
            }elseif ($custom_low_price && $custom_high_price) {
                $map['o.bid_start_price'] = array(array('egt', $custom_low_price*10000), array('elt', $custom_high_price*10000));
            } else {
                if ($price_range && is_array($price_range) && !in_array('-1',$price_range)) {
                    $where = array();
                    $arr = array();
                    foreach ($price_range as $k => $v) {
                        switch ($v) {
                            case '1':
                                $arr[] = "(o.bid_start_price < '50000')";
                                break;
                            case '2':
                                $arr[] = "(o.bid_start_price >= '50000' AND o.bid_start_price <= '100000')";
                                break;
                            case '3':
                                $arr[] = "(o.bid_start_price >= '100000' AND o.bid_start_price <= '200000')";
                                break;
                            case '4':
                                $arr[] = "(o.bid_start_price > '200000')";
                                break;
                        }
                    }
                    $where['_string'] = implode(' OR ', $arr);
                    //$where['_logic'] = 'or';
                    $map['_complex'] = $where;
                }
            }
    }

    //处理年限查询条件
    private function age_range_map(&$map,$age_range){
        if ($age_range && is_array($age_range) && !in_array('-1',$age_range)) {
            $arr = array();
            foreach ($age_range as $k => $v) {
                switch ($v) {
                    case '1':
                        $arr[] = "(c.first_reg_date > '" . date('Y-m-d', strtotime('-3 year')) . "')";
                        break;
                    case '2':
                        $arr[] = "(c.first_reg_date >= '" . date('Y-m-d', strtotime('-6 year')) . "' AND c.first_reg_date <= '" . date('Y-m-d', strtotime('-3 year')) . "')";
                        break;
                    case '3':
                        $arr[] = "(c.first_reg_date > '" . date('Y-m-d', strtotime('-10 year')) . "' AND c.first_reg_date <= '" . date('Y-m-d', strtotime('-6 year')) . "')";
                        break;
                    case '4':
                        $arr[] = "(c.first_reg_date <=   '" . date('Y-m-d', strtotime('-10 year')) . "')";
                        break;
                }
            }
            $map[1] = implode(' OR ', $arr);
        }
    }

    //处理综合车况查询条件
    private function condition_level_map(&$map,$condition_level=array()){
        if ($condition_level && is_array($condition_level) && !in_array('-1',$condition_level)) {
            $com_state = array();
            $car_level = array();
            foreach ($condition_level as $value) {
                preg_match("/([0-9]+)([a-zA-Z]+)/", $value, $matches);
                $com_state[] = $matches[1];
                $car_level[] = $matches[2];
            }
            //综合车况
            if ($com_state) {
                $map['c.composite_state'] = array('in', $com_state ? array_unique($com_state) : array(0));
            }
            //事故等级
            if ($car_level) {
                $map['c.accident_level'] = array('in',$car_level?array_unique($car_level):array(0));
            }
        }
    }

    /**
     * 根据筛选条件获取拍单个数
     */
    public function order_stat(){
           $count = $this->get_list(true);
           $this->api_200($count);
    }

}